package net.mikoo.seals.agent.biz.services.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import net.mikoo.seals.agent.biz.mapper.client.CompanyMapper;
import net.mikoo.seals.agent.biz.mapper.client.MemberMapper;
import net.mikoo.seals.agent.biz.services.MemberServices;
import net.mikoo.seals.agent.common.BaseServices;
import net.mikoo.seals.agent.common.PageModel;
import net.mikoo.seals.agent.common.WebContext;
import net.mikoo.seals.agent.common.exception.ParametersException;
import net.mikoo.seals.agent.common.utils.IPUtil;
import net.mikoo.seals.agent.common.utils.MD5Util;
import net.mikoo.seals.agent.model.MemberQuery;
import net.mikoo.seals.agent.model.Party;
import net.mikoo.seals.agent.model.Person;
import net.mikoo.seals.agent.model.UserLogin;

public class MemberServicesImpl extends BaseServices implements MemberServices {

	private Logger logger = LoggerFactory.getLogger(MemberServicesImpl.class);

	@Autowired
	private MemberMapper memberMapper;
	
	@Autowired
	private CompanyMapper companyMapper;

	@Override
	public PageModel<Party> getToPageByQuery(MemberQuery query) {
		List<Party> datas = memberMapper.selectToPageByQuery(query);
		Integer total = memberMapper.countToPageByQuery(query);
		PageModel<Party> pm = new PageModel<>(total, datas);
		return pm;
	}

	@Override
	public Party create(Party party) {

		return clientTransactionTemplate.execute(new TransactionCallback<Party>() {

			@Override
			public Party doInTransaction(TransactionStatus status) {
				try {

					// 验证当事人字段
//					String partyType = party.getPartyType();
//					if (StringUtils.isBlank(partyType)) {
//						throw new ParametersException("partyType is blank");
//					}
					
					Long companyId = party.getCompanyId();
					if (companyId == null) {
						throw new ParametersException("companyId is blank");
					}

					String partyStatus = party.getPartyStatus();
					if (StringUtils.isBlank(partyStatus)) {
						throw new ParametersException("partyStatus is blank");
					}

					// 验证用户名
					UserLogin userLogin = party.getUserLogin();
					Person person = party.getPerson();
					String userLoginId = userLogin.getUserLoginId();
					if (StringUtils.isBlank(userLoginId)) {
						throw new ParametersException("userLoginId is blank");
					}

					boolean b = isExist(userLoginId, null, "username");
					if (b) {
						throw new ParametersException("登陆账户已存在");

					}
					// 验证密码字段
					String password = userLogin.getCurrentPassword();
					if (StringUtils.isBlank(password)) {
						throw new ParametersException("password is blank");
					}

					String email = person.getEmail();
					if (StringUtils.isNotBlank(email) && isExist(email, null, "email")) {
						throw new ParametersException("邮箱账户已存在");
					}

					String mobile = person.getMobile();
					if (StringUtils.isNotBlank(mobile) && isExist(mobile, null, "mobile")) {
						throw new ParametersException("手机号码已存在");
					}

					// 创建party
					party.setUserLoginId(userLogin.getUserLoginId());
					party.setCreatedTime(new Date());
					party.setIsSystem("Y");
					memberMapper.insertBackPrimaryKey(party);

					// 创建登录帐户

					userLogin.setCurrentPassword(MD5Util.Md5(userLogin.getCurrentPassword()));
					userLogin.setPartyId(party.getPartyId());
					userLogin.setRegisterTime(new Date());
					userLogin.setRegisterIp(IPUtil.getRemoteAddr(WebContext.getRequest()));
					userLogin.setIsSystem("Y");
					memberMapper.insertUserLogin(userLogin);

					// 创建人员信息
					person.setUserLoginId(userLogin.getUserLoginId());
					person.setPartyId(party.getPartyId());
					memberMapper.insertPerson(person);
					
					
					companyMapper.updateManagerAccount(party.getCompanyId(),userLogin.getUserLoginId());
					
					return party;

				} catch (ParametersException e) {
					logger.error("", e);
					status.setRollbackOnly();
					throw e;
				} catch (Exception e) {
					logger.error("", e);
					status.setRollbackOnly();
					throw e;
				}

			}

			

		});

	}
	
	
	/**
	 * 判断字段是否唯一
	 * @param verifykey
	 * @param excludeKey
	 * @param type
	 * @return
	 */
	private boolean isExist(String verifykey, String excludeKey, String type) {
		boolean b = false;
		switch (type) {
			case "username":
				
				UserLogin userLogin = memberMapper.selectByUserLoginId(verifykey);
				if (userLogin == null) {
					b = false;
				} else {
					
					b = true;
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(userLogin.getUserLoginId())) {
							b = false;
						}
					}
				}
				break;
			
			case "mobile":
				Person mPerson = memberMapper.selectByMobile(verifykey);
				if (mPerson == null) {
					b = false;
				} else {
					
					b = true;
					
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(mPerson.getMobile())) {
							b = false;
						}
					}
				}
				break;
			
			case "email":
				
				Person ePerson = memberMapper.selectByEmail(verifykey);
				if (ePerson == null) {
					b = false;
				} else {
					b = true;
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(ePerson.getEmail())) {
							b = false;
						}
					}
				}
				
				break;
			default:
				
				break;
		}
		
		return b;
	}

	@Override
	public Party getByUserLoginId(String userLoginId) {
		// TODO Auto-generated method stub
		return null;
	}

}
